<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>继电器</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="zepto.js.gz"></script>
	<link rel="stylesheet" href="mini-nord.css.gz">
</head>

<body>
	<header>
		<a href="./index.html" class="button">状态</a>
		<a href="./wifi.html" class="button">无线</a>
		<a href="./mqtt.html" class="button">MQTT</a>
		<a href="./relay.html" class="button">继电器</a>
	</header>
	<div class="tabs">
		<input type="radio" name="tab-group" id="relay_0" checked aria-hidden="true">
		<label for="relay_0" aria-hidden="true">继电器 1</label>
		<input type="radio" name="tab-group" id="relay_1" aria-hidden="true">
		<label for="relay_1" aria-hidden="true">继电器 2</label>
		<input type="radio" name="tab-group" id="relay_2" aria-hidden="true">
		<label for="relay_2" aria-hidden="true">继电器 3</label>
	</div>

	<div>状态：
		<span id="r_state"></span>
	</div>
	<form>
		<fieldset>
			<legend>选项</legend>
			<div class="input-group">
				<input type="checkbox" id="en">
				<label for="en">使能</label>
			</div>
			<div class="input-group">
				<input type="checkbox" id="m_p" name="w_mode">
				<label for="m_p">脉冲</label>
			</div>
		</fieldset>
		<div class="div_pulse">
			<fieldset>
				<legend>脉冲时间（秒）</legend>
				<div class="input-group">
					<label for="t_on">打开</label>
					<input type="num" id="t_on" size="5">
				</div>
				<div class="input-group">
					<label for="t_off">关闭</label>
					<input type="num" id="t_off" size="5">
				</div>
			</fieldset>
		</div>
		<fieldset>
			<legend>手动</legend>
			<div class="input-group">
				<input type="checkbox" id="manual">
				<label for="manual">手动</label>
			</div>

			<div class="input-group">
				<input type="num" id="duration" placeholder="" value="1" size="5">
				<label for="duration">分</label>
			</div>
			<div class="input-group">
				<button id="btnManual" class="primary" value="0">开启</button>
				<div id="progress"></div>
			</div>
		</fieldset>
	</form>
	<form>
		<fieldset>
			<legend>计划（分）</legend>
			<div class="container">
				<div class="row">
					<div class="col-sm-2">#</div>
					<div class="col-sm-4">开始</div>
					<div class="col-sm-3">时长</div>
				</div>
				<div class="row">
					<div class="col-sm-2">1</div>
					<div class="col-sm-4">
						<input id="a0" type="time" value="00:00">
					</div>
					<div class="col-sm-3">
						<input id="a1" type="num" value="0" size="6">
					</div>
				</div>
				<div class="row">
					<div class="col-sm-2">2</div>
					<div class="col-sm-4">
						<input id="b0" type="time" value="00:00">
					</div>
					<div class="col-sm-3">
						<input id="b1" type="num" value="0" size="6">
					</div>
				</div>
				<div class="row">
					<div class="col-sm-2">3</div>
					<div class="col-sm-4">
						<input id="c0" type="time" value="00:00">
					</div>
					<div class="col-sm-3">
						<input id="c1" type="num" value="0" size="6">
					</div>
				</div>
				<div class="row">
					<div class="col-sm-2">4</div>
					<div class="col-sm-4">
						<input id="d0" type="time" value="00:00">
					</div>
					<div class="col-sm-3">
						<input id="d1" type="num" value="0" size="6">
					</div>
				</div>
				<div class="row">
					<div class="col-sm-2">5</div>
					<div class="col-sm-4">
						<input id="e0" type="time" value="00:00">
					</div>
					<div class="col-sm-3">
						<input id="e1" type="num" value="0" size="6">
					</div>
				</div>
				<div class="row">
					<div class="col-sm-2">6</div>
					<div class="col-sm-4">
						<input id="f0" type="time" value="00:00">
					</div>
					<div class="col-sm-3">
						<input id="f1" type="num" value="0" size="6">
					</div>
				</div>
			</div>
			<div>
				<button id="save" class="primary">保存</button>
			</div>
		</fieldset>
	</form>
	<br/>
	<footer class="sticky">
		&copy; 2017
		<a href="#">yusp</a>
		QQ:475060921
	</footer>
</body>

</html>
<script>
	var idx = 0;
	var r = /^[0-9]*$/;
	var ws;
	var uri = "ws://" + location.host + "/rpc/";
	//var uri = "ws://192.168.0.119/rpc/";
	//var uri = "ws://192.168.100.102/rpc/";
	$(document).ready(function () {
		/* ws connect */
		function ws_connect() {
			ws = new WebSocket(uri);
			ws.onopen = function (ev) {
				console.log(ev);
				get_config();
			};
			ws.onclose = function (ev) {
				console.log(ev);
				setTimeout(ws_connect, 1000);
			};
			ws.onmessage = function (ev) {
				console.log('message', ev);
				try {
					var data = JSON.parse(ev.data);
					if (data.hasOwnProperty("error")) {
						console.log(data.error.message);
					}
					else {
						if (data.tag == "get_config") {
							msg_get_config(data);
						} else if (data.tag == "manual_open") {
							msg_manual_open(data);
						} else if (data.tag == "save_cfg") {
							msg_save_cfg();
						} else if (data.tag == "state_update") {
							msg_state_update(data);
						}
						else if (data.tag == "save") {
							alert("已保存。");
						}
					}
				} catch (e) {
					console.log(e);
				}
			};
			ws.onerror = function (ev) {
				console.log(ev);
				ws.close();
			};
		}

		ws_connect();

		//input
		$("#relay_0").click(function (ev) {
			idx = 0;
			get_config();
		});
		$("#relay_1").click(function (ev) {
			idx = 1;
			get_config();
		});
		$("#relay_2").click(function (ev) {
			idx = 2;
			get_config();
		});

		function manual_open(pinState) {
			ws.send(JSON.stringify({
				method: "my.manual",
				args: {
					idx: idx,
					duration: parseInt($("#duration").val()),
					enable: $("#en").is(":checked"),
					manual: $("#manual").is(":checked"),
					pulse: $("#m_p").is(":checked"),
					state: pinState
				},
				tag: "manual_open"
			}));
		}

		//refresh data
		function get_config() {
			ws.send(JSON.stringify({
				method: "my.get",
				args: { type: "relay", idx: idx },
				tag: "get_config"
			}));
		}

		//get config
		function msg_get_config(data) {
			if (data.result.idx == idx) {
				$("#idx").val(data.result.idx);
				$("#title").val(data.result.title);
				$("#en").prop("checked", data.result.enable);
				$("#btnManual").text(data.result.state == true ? "关闭" : "开启");
				$("#r_state").html(data.result.state == true ? "已打开" : "已关闭");
				$("#m_p").prop("checked", data.result.pulse);
				$("#t_on").val(data.result.t_on);
				$("#t_off").val(data.result.t_off);
				try {
					var s = JSON.parse(data.result.schedule);
					$("#a0").val(t(s.a0));
					$("#a1").val(s.a1);
					$("#b0").val(t(s.b0));
					$("#b1").val(s.b1);
					$("#c0").val(t(s.c0));
					$("#c1").val(s.c1);
					$("#d0").val(t(s.d0));
					$("#d1").val(s.d1);
					$("#e0").val(t(s.e0));
					$("#e1").val(s.e1);
					$("#f0").val(t(s.f0));
					$("#f1").val(s.f1);
				} catch (e) {
					alert("err:schedule," + e);
				}
			}
		}
		function msg_manual_open(data) {
			$("#progress").removeClass("spinner-donut");
			if (data.result.state) {
				$("#r_state").html("已打开");
				$("#btnManual").text("关闭");

			} else {
				$("#r_state").html("已关闭");
				$("#btnManual").text("开启");
			}
		}
		function msg_state_update(data) {
			if (idx == data.idx) {
				$("#r_state").html(data.state == true ? "已打开" : "已关闭");
				$("#btnManual").text(data.state == true ? "关闭" : "开启");
			}
		}
		// save to server
		$("#save").click(function (ev) {
			ev.preventDefault();
			if (!validate()) return false;
			var priority = 0;
			var s = {
				a0: c($("#a0").val()),
				a1: parseInt($("#a1").val()),
				b0: c($("#b0").val()),
				b1: parseInt($("#b1").val()),
				c0: c($("#c0").val()),
				c1: parseInt($("#c1").val()),
				d0: c($("#d0").val()),
				d1: parseInt($("#d1").val()),
				e0: c($("#e0").val()),
				e1: parseInt($("#e1").val()),
				f0: c($("#f0").val()),
				f1: parseInt($("#f1").val())
			};
			var d = {
				method: "Config.Set",
				args: {
					config: {
						r0: {
							enable: $("#en").is(":checked"),
							title: $("#title").val(),
							priority: 0,
							pulse: $("#m_p").is(":checked"),
							on: parseInt($("#t_on").val()),
							off: parseInt($("#t_off").val()),
							schedule: JSON.stringify(s)
						}
					}
				},
				tag: "save_cfg"
			}
			ws.send(JSON.stringify(d).replace(/r0/, "r" + idx.toString()));
			//
		});

		function msg_save_cfg() {
			ws.send(JSON.stringify({
				method: "Config.Save",
				args: { reboot: false },
				tag: "save"
			}));
		}

		function c(s) {
			var n = s.split(":");
			return parseInt(n[0]) * 3600 + parseInt(n[1]) * 60;
		}

		function t(s) {
			var h = s / 3600;
			var m = (s - h * 3600) / 60;
			return printf("%02d", h) + ":" + printf("%02d", m);
		}
		// 按钮：手动
		$("#btnManual").click(function (ev) {
			ev.preventDefault();
			if (!r.test($("#duration").val())) {
				$("#duration").css("color", "red");
				return false;
			}
			$("#progress").addClass("spinner-donut");
			//send_cmd($(this).text() == "开启" ? true : false);
			manual_open($(this).text() == "开启" ? true : false);
		});

		function printf() {
			var as = [].slice.call(arguments), fmt = as.shift(), i = 0;
			return fmt.replace(/%(\w)?(\d)?([dfsx])/ig, function (_, a, b, c) {
				var s = b ? new Array(b - 0 + 1).join(a || '') : '';
				if (c == 'd') s += parseInt(as[i++]);
				return b ? s.slice(b * -1) : s;
			})
		}

		function validate() {
			var result = true;
			$.each([$("#a1"), $("#b1"), $("#c1"), $("#d1"), $("#e1"), $("#f1"), $("#t_on"), $("#t_off")],
				function (index, item) {
					if (!r.test(item.val())) {
						result = false;
						item.css("color", "red");
					} else {
						if (parseInt($("#t_on").val()) <= 0) {
							result = false;
							$("#t_on").css("color", "red");
						}
						if (parseInt($("#t_off").val()) <= 0) {
							result = false;
							$("#t_off").css("color", "red");
						}
					}
				});
			return result;
		}
		// end: ready
	});
</script>